<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { useJinnongStore } from "../stores/jinnong";
import qs from "qs";
import moment from "moment";
import { ElButton } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";

const route = useRoute();
const jinnongStore = useJinnongStore();
const error = ref(false);
const status = ref(false);
const pause = ref(false);
const slow = ref(false);
const mute = ref(true);
const hikPlayer = ref();
const MSE_IS_SUPPORT = !!window.MediaSource; // 是否支持mse
const mode = MSE_IS_SUPPORT ? 0 : 1;


onMounted(() => {
  createPlayer();
});

jinnongStore.$subscribe((mutation, state) => {
  const playURL = state.playbackUrl.replace(
    "1.30.17.186",
    "isecure.jinnongjianguan.com"
  );
  const timeSeq = qs.parse(playURL.split("?")[1]);
  const player = hikPlayer.value;

  player.JS_Play(
    playURL,
    { playURL, mode },
    0,
    moment(timeSeq.beginTime).format("YYYY-MM-DDTHH:mm:ss[Z]"),
    moment(timeSeq.endTime).format("YYYY-MM-DDTHH:mm:ss[Z]")
  );
});

function loadData() {
  jinnongStore
    .getPlaybackUrl({
      beginTime: route.query.start.replace(" ", "+"),
      endTime: route.query.end.replace(" ", "+"),
      protocol: "wss",
      recordLocation: 1,
      expand: "transcode=2&videotype=h264&audiotype=aac",
      cameraIndexCode: route.query.device,
    })
    .then(
      () => {
        console.log("ok");
      },
      (err) => {
        error.value = true;
        document.getElementById("player-container-0").innerHTML += `<div class="bad_video">${err.code}:  取流失败，详情根据错误码在运管后台进行查询.</div>`;
        ElMessageBox.alert(
          `<h3>取流失败</h3><div> </div><div>错误代码：${err.code}\n</div><div>错误详情：${err.response.data.msg}</div>`,
          `视频回放`,
          {
            dangerouslyUseHTMLString: true,
          }
        );
      }
    );
}

function createPlayer() {
  const IS_MOVE_DEVICE = document.body.clientWidth < 992;
  const player = new window.JSPlugin({
    szId: "player",
    szBasePath: "./hik",
    iMaxSplit: 1,
    iCurrentSplit: 1,
    openDebug: false,
    oStyle: {
      borderSelect: IS_MOVE_DEVICE ? "#000" : "#FFCC00",
    },
  });
  hikPlayer.value = player;

  window.addEventListener("resize", () => {
    hikPlayer.value.JS_Resize();
  });
  player.JS_SetWindowControlCallback({
    pluginErrorHandler: function (iWndIndex, iErrorCode, oError) {
      ElMessageBox.alert(
        `<h3>取流失败</h3><div> </div><div>错误代码：${iErrorCode}\n</div><div>错误详情：${oError.statusString}</div>`,
        `视频回放`,
        {
          dangerouslyUseHTMLString: true,
        }
      );
    },
    firstFrameDisplay: function (iWndIndex, iWidth, iHeight) {
      status.value = true;
    },
    StreamEnd: function (iWndIndex) {
      status.value = false;
    },
  });
  loadData();
}

function startPlay() {
  loadData();
}

function stopPlay() {
  hikPlayer.value.JS_Stop(0).then(() => {
    status.value = false;
    pause.value = false;
    mute.value = true;
  });
}

function togglePlay() {
  status.value = !status.value;
  if (status.value) {
    startPlay();
  } else {
    stopPlay();
  }
}

function togglePause() {
  pause.value = !pause.value;
  if (pause.value) {
    hikPlayer.value.JS_Pause(0);
  } else {
    hikPlayer.value.JS_Resume(0);
  }
}

function toggleSlowPlay() {
  slow.value = !slow.value;
  if (slow.value) {
    hikPlayer.value.JS_Slow(0);
  } else {
    hikPlayer.value.JS_Fast(0);
  }
}

function toggleSound() {
  mute.value = !mute.value;
  if (mute.value) {
    hikPlayer.value.JS_OpenSound(0);
  } else {
    hikPlayer.value.JS_CloseSound(0);
  }
}
</script>

<template>
  <div id="player"></div>
  <div class="buttons">
    <el-button
      class="button"
      :type="status ? 'danger' : 'primary'"
      size="large"
      :disabled="error"
      @click="togglePlay"
      >{{ status ? "停止" : "播放" }}</el-button
    >
    <el-button
      class="button"
      type="success"
      size="large"
      :disabled="!status || error"
      @click="togglePause"
      >{{ pause ? "继续" : "暂停" }}</el-button
    >
    <el-button
      class="button"
      type="warning"
      size="large"
      :disabled="!status || error"
      @click="toggleSlowPlay"
      >{{ slow ? "恢复" : "慢速" }}</el-button
    >
    <el-button
      class="button"
      color="#626aef"
      size="large"
      :disabled="!status || error"
      @click="toggleSound"
      >{{ mute ? "开启" : "关闭" }}声音</el-button
    >
  </div>
</template>

<style>
::-webkit-media-controls {
  display: none !important;
}

#player {
}

@media screen and (max-width: 991px) {
  #player {
    width: calc(100vw - 16px);
    height: calc((100vw - 16px) * 5 / 8);
  }
}

@media screen and (min-width: 992px) {
  #player {
    width: calc(50vw - 8px);
    height: calc((50vw - 8px) * 5 / 8);
  }
}

.buttons {
  display: flex;
  justify-content: space-around;
  margin-top: 16px;
}

.buttons .button {
  flex: 1;
}


#player .bad_video {
  display: flex;
  color: #fff;
  font-weight: 500;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #ff9f9f;
  z-index: 100;
}
</style>
